package com.systar.activity.parse;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import com.google.common.eventbus.EventBus;
import com.systar.activity.state.FileActivity;

public class SessionFileParserSax extends SessionFileParser
{

	private class XSessionHandler extends DefaultHandler
	{
		private String currentEventKind;
		private String currentModulePriority;
		private StringBuffer message;

		XSessionHandler()
		{
			currentEventKind = null;
			currentModulePriority = null;
			message = null;
		}

		@Override
		public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException
		{
			if ("event".equals(qName))
			{
				currentEventKind = attrs.getValue("kind");
			}
			else if ("module".equals(qName))
			{
				currentModulePriority = attrs.getValue("priority");
			}
			else if ("message".equals(qName))
			{
				if (nbErr > 0)
					message = new StringBuffer();
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException
		{
			if ("message".equals(qName))
			{
				// raise event
				submit(currentEventKind, currentModulePriority, (message != null ? message.toString() : null));
				// clear data
				message = null;
			}
		}

		@Override
		public void endDocument() throws SAXException
		{
			flush();
		}

		@Override
		public void characters(char[] chars, int start, int length)
		{
			if (message != null)
				message.append(chars, start, length);
		}
	}

	public SessionFileParserSax(FileActivity activity, EventBus eventBus)
	{
		super(activity, eventBus);
	}

	@Override
	public Integer call() throws Exception
	{
		nbInfo = nbWarn = nbErr = 0;
		XMLReader saxReader = XMLReaderFactory.createXMLReader();
		saxReader.setContentHandler(new XSessionHandler());

		saxReader.parse(new InputSource(activity.getReader()));
		return 0;
	}

}
